#!/usr/bin/env python
# -*- coding: utf-8 -*- 

#Kiwi Bot
#Copyright (C) 2009 Mathieu "MathX" Xhonneux
#Modified by @nge1nCorsic4 in 2010

#This program is free software; you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation; either version 2 of the License, or
#(at your option) any later version.

#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.

#You should have received a copy of the GNU General Public License along
#with this program; if not, write to the Free Software Foundation, Inc.,
#51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

import re, time, Queue, threading, atexit, traceback, sys
from subprocess import call
import kiwi, kiwi.events, kiwi.parser, kiwi.config, kiwi.log, kiwi.gameInteraction, kiwi.lang
class main:
	def __init__(self):
		self.config = kiwi.config.configuration()
		self.lang = kiwi.lang.Lang(self,'base')
		print self.lang.lang('', '10001')
		atexit.register(self.onStop)
		self.log = kiwi.log.logging()
		self.eventsList = Queue.Queue(0)
		self.working = True
		threading.Thread(target=self.eventManager).start()
		try:
			self.mainLoop()
		except KeyboardInterrupt:
			self.working = False
			self.stopMain()
	def mainLoop(self):
		self.eventsList.put(kiwi.events.Event(kiwi.events.EVT_START))
		self.f = open(self.config.server.log_game,'r')
		self.f.seek(0,2)
		while self.working:
			line = self.readline()
			if line:
				try:
					event = kiwi.parser.getEvent(line)
				except Exception:
					print self.lang.lang('', '10002'), self.log.date()
					self.log.error(traceback.format_exc().strip())
				if event:
					self.eventsList.put(event)
			time.sleep(0.001)
	def readline(self):
		while 1:
			if self.working:
				line = self.f.readline()
				if line:
					break
				time.sleep(0.001)
			else:
				break
		if line[-1] != '\n':
			newline = self.readline()
			if newline:
				line += newline
		return re.sub(r'\^[0-9a-z]', '',line.strip())
	def eventManager(self):
		self.interaction = kiwi.gameInteraction.Interaction(self)
		while self.working:
			event = self.eventsList.get()
			try:
				self.interaction.handleEvent(event)
			except Exception:
				print self.lang.lang('', '10003'), self.log.date()
				self.log.error(traceback.format_exc().strip())
	def stopMain(self):
		self.eventsList.put(kiwi.events.Event(kiwi.events.EVT_STOP))
		self.working = False
	def onStop(self):
		self.log.warn(self.lang.lang('', '10004'))
		print self.lang.lang('', '10004')
		self.stopMain()
		time.sleep(2)
		self.f.close()
	def reboot(self,fullpath):
		self.onStop()
		call([fullpath, "restart"])
mainLoop = main()